#
# peerscape.profile.links
#
# Copyright 2008-2009 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Maintain links from personal or group profiles to other datasets.

Links are useful for navigation and data replication.

>>> from peerscape import DB
>>> db = DB()
>>> p = db.init_persona('Test User')
>>> iid1 = db.create_dataset('One', 'content')
>>> iid2 = db.create_dataset('Two', 'content')
>>> iid3 = db.create_dataset('Three', 'other')

>>> db.list_links(p)
[]

>>> db.add_link(p, iid1, public=True)
>>> db.add_link(p, iid2, public=True)
>>> db.add_link(p, iid3, public=False)
>>> db.list_links(p, field='iid') == [iid1, iid2, iid3]
True
>>> db.list_links(p, field='title')
[u'One', u'Two', u'Three']
>>> db.list_links(p, field='title', type='content')
[u'One', u'Two']

>>> db.list_links(p, field='type')
[u'content', u'content', u'other']
>>> db.list_links(p, field='type', patch_missing_type=False)
[u'content', u'content', u'other']

>>> event = db.get_last_event(p)
>>> event['comment']
u'Added link.'
>>> event['iid'] == iid3
True
>>> db.post_event(p, 'Testing...', public=False)
>>> db.add_link(p, iid3, public=False)
>>> db.get_last_event(p)['comment']
u'Testing...'

>>> db.add_link(p, iid2, public=False)
>>> db.add_link(p, iid3, True, dict(extra='!!!'))
>>> db.list_links(p, field='title')
[u'One', u'Three', u'Two']
>>> db.list_links(p, field='extra')
[None, u'!!!', None]

>>> event = db.get_last_event(p)
>>> event['comment']
u'Added link.'
>>> event['iid'] == iid3
True
>>> db.post_event(p, 'Testing...', public=True)
>>> db.add_link(p, iid3, True, dict(extra='!!!'))
>>> db.get_last_event(p)['comment']
u'Testing...'

>>> db.clear_link(p, iid3)
>>> db.list_links(p, field='title')
[u'One', u'Two']

>>> db.clear_persona()
>>> db.list_links(p, field='title')
[u'One']
>>> db.list_links(p) == [{'iid': iid1, 'public': True,
...                       'title': 'One', 'type': 'content'}]
True

>>> db.get_last_event(p)['comment']
u'Testing...'

>>> db.close()
"""

from __future__ import with_statement

from hashlib import sha1

from peerscape.core.iid import is_canonical_iid, hex, hex_to_buffer

PUBLIC_FOLDER = '/public/link/'
RESTRICTED_FOLDER = '/restricted/link/'

class ProfileLinksDBMixin(object):
    def list_links(self, src, type=None, field=None, patch_missing_type=True):
        """
        Return info about a profile's links as a list of dictionaries.

        Only the visible links are returned.

        The optional type can be specified to narrow the set of links
        considered.  The optional field name can be specified to
        return just that field instead of the whole dictionary.
        """
        objects = []
        with self.read_transaction():
            def add(obj, hash, public):
                if patch_missing_type and 'type' not in obj:
                    obj['type'] = self.get_dataset_type(obj['iid'])
                    if obj['type'] is None:
                        return

                if type is None or obj['type'] == type:
                    if _check(obj, hash, public):
                        objects.append(obj.get(field) if field else obj)

            for hash in self.list(src, PUBLIC_FOLDER):
                obj = self.get_json(src, PUBLIC_FOLDER + hash)
                add(obj, hash, public=True)

            try:
                cipher = self.get_group_cipher(src)
            except LookupError:
                return objects

            for hash in self.list(src, RESTRICTED_FOLDER):
                obj = self.get_json(src, RESTRICTED_FOLDER + hash,
                                  cipher=cipher)
                add(obj, hash, public=False)

            return objects

    def add_link(self, src, dst, public=False, extra_info={}):
        """
        Create a link from the source profile to a destination dataset.

        The link can be either public or for friends/members only.  It
        will include the type and title of the destination dataset as
        the values of "type" and "title", respectively.  The optional
        extra_info parameter can be used to specify additional fields.

        If a link from the source to the destination already exists,
        it is replaced.
        """
        with self.write_transaction():
            type = self.get_dataset_type(dst)
            if type is None:
                raise LookupError('Dataset not found.')

            title = self.get_text(dst, '/info/title.txt')
            if not title:
                raise LookupError('No dataset title.')

            obj = dict(iid=hex(dst), public=public, type=type, title=title)
            obj.update(extra_info)

            hash = _hexhash(dst)
            public_path = PUBLIC_FOLDER + hash
            restricted_path = RESTRICTED_FOLDER + hash

            before = self.get_current_mark()
            if public:
                self.put(src, public_path, obj)
                self.delete(src, restricted_path)
            else:
                cipher = self.get_group_cipher(src)
                self.put(src, restricted_path, obj, cipher=cipher)
                self.delete(src, public_path)

            after = self.get_current_mark()
            if before != after:
                self.post_event(src, 'Added link.', dst, public=public)

    def clear_link(self, src, dst):
        """
        Remove the specified link.
        """
        with self.write_transaction():
            hash = _hexhash(dst)
            self.delete(src, PUBLIC_FOLDER + hash)
            self.delete(src, RESTRICTED_FOLDER + hash)
            self.post_nonevent(src)

def _check(obj, hash, public):
    iid = obj.get('iid')
    type = obj.get('type')
    title = obj.get('title')
    is_public = obj.get('public')
    return (is_public == public
            and isinstance(title, (str, unicode)) and title
            and isinstance(type, (str, unicode))
            and is_canonical_iid(iid) and _hexhash(iid) == hash)

def _hexhash(iid):
    return sha1(hex_to_buffer(iid)).hexdigest()

if __name__ == '__main__':
    import doctest
    doctest.testmod()
